package com.siki.Utils.fileUtils;

import com.siki.Utils.SystemMsgJsonResponse;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;

@Component
public class FileUtils {

    private static String path;

    private static String return_file_path;

    @Value("${siki-path}")
    public void setPath(String path) {
        FileUtils.path = path;
    }

    @Value("${return-path}")
    public void setReturn_file_path(String return_file_path) {
        FileUtils.return_file_path = return_file_path;
    }

    public static String upload_file(MultipartFile file){
        String file_name = file.getOriginalFilename();
        //生成新的文件名
        String new_file_name = FileNameUtils.getFileName(file_name);

        //确定上传路径
        String realPath = path + "/" + new_file_name;
        File dest = new File(realPath);

        //判断文件父目录是否存在,不存在则创建
        if(!dest.getParentFile().exists()){
            dest.getParentFile().mkdir();
        }

        try {
            //保存文件
            file.transferTo(dest);
            return realPath;
        } catch (IOException e) {
            return e.getMessage();
        }
    }


    @ApiOperation(value = "[文件] - 下载文件", httpMethod = "GET", consumes = "application/form-data")
    @GetMapping(value = "/download/{filename}")
    public SystemMsgJsonResponse download(HttpServletResponse response, @ApiParam("文件名称") @PathVariable("filename") String fileName){
        File file = new File(return_file_path +'/'+ fileName);
        if(!file.exists()){
            return SystemMsgJsonResponse.fail("文件不存在");
        }
        response.reset();
//        response.setContentType("application/form-data");
//        response.setCharacterEncoding("utf-8");
        response.setContentLength((int) file.length());
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName );

        try(BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));) {
            byte[] buff = new byte[1024];
            OutputStream os  = response.getOutputStream();
            int i = 0;
            while ((i = bis.read(buff)) != -1) {
                os.write(buff, 0, i);
                os.flush();
            }
        } catch (IOException e) {
            return SystemMsgJsonResponse.fail(e.getMessage());
        }
        return SystemMsgJsonResponse.success("下载成功");
    }
}
